package com.suse.service.user.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.suse.common.util.jwt.JwtUtil;
import com.suse.service.user.entity.User;
import com.suse.service.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 微信前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-16 15:05
 */
@Api(tags = "微信接口")
@Controller
@RequestMapping("/api/ucenter/wx")
// @CrossOrigin 使用了gateway网关解决跨域这里不能再加跨域注解
public class WxController {

    private static final String APP_ID = "wxed9954c01bb89b47";

    private static final String SECRET = "a7482517235173ddb4083788de60b90e";

    private static final String REDIRECT_URI = "http://localhost:8160/api/ucenter/wx/callback";

    @Resource
    private UserService userService;

    @GetMapping("/callback")
    public String callback(String code) {
        // 第二步：携带授权码向授权服务器发送 http 请求，获取访问令牌
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String, Object> param = new HashMap<>();
        param.put("appid",APP_ID);
        param.put("secret",SECRET);
        param.put("code",code);
        param.put("grant_type","authorization_code");
        String body = HttpRequest.get(accessTokenUrl)
                .form(param)
                .execute()
                .body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        User user = userService.getUserByOpenid(openid);
        // 判断用户是否已存在
        if (ObjectUtil.isNull(user)) {
            // 第三步，携带访问令牌向资源服务器发送请求，获取用户信息
            String userinfoUrl = "https://api.weixin.qq.com/sns/userinfo";
            param = new HashMap<>();
            param.put("access_token",accessToken);
            param.put("openid",openid);
            body = HttpRequest.get(userinfoUrl)
                    .form(param)
                    .execute()
                    .body();
            jsonObject = JSONObject.parseObject(body);
            String nickname = jsonObject.getString("nickname");
            String headimgurl = jsonObject.getString("headimgurl");
            user = new User();
            user.setOpenid(openid);
            user.setName(nickname);
            user.setAvatar(headimgurl);
            userService.save(user);
        }
        // 创建 token
        String token = JwtUtil.createToken(user);
        return "redirect:http://localhost:3000?token=" + token;
    }

    @ApiOperation(value = "获取微信登录二维码")
    @GetMapping("/login")
    public String getWxCode() {
        // 第一步：向资源拥有者发送请求，获取授权码
        String redirectUri = REDIRECT_URI;
        try {
            redirectUri = URLEncoder.encode(redirectUri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + APP_ID + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_login&state=zxjy#wechat_redirect";
        return "redirect:" + url;
    }

}
